package com.zg.autoflow.web;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zg.autoflow.req.*;
import com.zg.autoflow.service.AutoflowStepService;
import com.zg.autoflow.vo.AutoflowStepAddVo;
import com.zg.autoflow.vo.AutoflowStepFormVo;
import com.zg.autoflow.vo.AutoflowStepPageVo;
import com.zg.common.core.R;
import com.zg.common.core.dao.BaseEntity;
import com.zg.common.core.dao.auth.AuthUser;
import com.zg.common.core.dao.auth.AuthUserDao;
import com.zg.common.core.dao.autoflow.dao.AutoflowStepDao;
import com.zg.common.core.dao.autoflow.dao.AutoflowStepFormDao;
import com.zg.common.core.dao.autoflow.dao.AutoflowStepPersonDao;
import com.zg.common.core.dao.autoflow.entity.AutoflowStep;
import com.zg.common.core.dao.autoflow.entity.AutoflowStepForm;
import com.zg.common.core.dao.autoflow.entity.AutoflowStepPerson;
import com.zg.common.core.dao.autoform.DiyForm;
import com.zg.common.core.dao.autoform.DiyFormDao;
import com.zg.common.core.dao.autoform.DiyView;
import com.zg.common.core.dao.autoform.DiyViewDao;
import com.zg.common.core.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author zg
*/
@RestController
@RequiredArgsConstructor
@Api(tags = {"流程环节配置"})
public class AutoflowStepController {
	private final AutoflowStepDao autoflowStepDao;
	private final AutoflowStepPersonDao autoflowStepPersonDao;
	private final AutoflowStepService autoflowStepService;
	private final AuthUserDao authUserDao;
	private final DiyViewDao diyViewDao;
	private final AutoflowStepFormDao autoflowStepFormDao;
	private final DiyFormDao formDao;

	@ApiOperation("新增环节")
	@PostMapping("/autoFlow/step/add")
	public R<?> add(@RequestBody @Valid AutoflowStepAddVo param) {
		AutoflowStep obj = autoflowStepService.add(param);
		return R.success(obj);
	}
	@ApiOperation("删除环节")
	@PostMapping("/autoFlow/step/del")
	public R<?> del(@RequestBody List<Long> idList) {
		autoflowStepService.del(idList);
		return R.success();
	}
	@ApiOperation("修改环节")
	@PostMapping("/autoFlow/step/update")
	public R<?> update(@RequestBody @Valid AutoflowStepUpdateReq param) {
		AutoflowStep obj = autoflowStepService.update(param);
		return R.success(obj);
	}
	@ApiOperation("修改环节处理人")
	@PostMapping("/autoFlow/step/updatePerson")
	public R<?> updatePerson(@RequestBody @Valid AutoflowStepUpdatePersonReq param) {
		AutoflowStep obj = autoflowStepDao.getById(param.getId());
		if (ObjectUtils.isEmpty(obj)) BusinessException.happen("环节id异常请检查");
		List<Long> personList = param.getPersonList();
		autoflowStepPersonDao.remove(new LambdaQueryWrapper<AutoflowStepPerson>().eq(AutoflowStepPerson::getStepId,param.getId()));
		personList.forEach(line->{
			AutoflowStepPerson autoflowStepPerson = new AutoflowStepPerson();
			autoflowStepPerson.setStepId(param.getId());
			autoflowStepPerson.setStepHandler(line);
			autoflowStepPersonDao.save(autoflowStepPerson);
		});
		return R.success(obj);
	}
	@ApiOperation("批量新增环节")
	@PostMapping("/autoFlow/step/batch")
		public R<?> batch(@RequestBody @Valid List<AutoflowStepBatchReq> param) {
		autoflowStepService.batchUpdate(param);
		return R.success();
	}
	@ApiOperation("查询流程所有环节")
	@PostMapping("/autoFlow/step/all")
	public R<List<AutoflowStep>> all(@RequestBody Long flowId) {
		if (ObjectUtils.isEmpty(flowId)){
			BusinessException.happen("流程id不能为空");
		}
		LambdaQueryWrapper<AutoflowStep> eq = new LambdaQueryWrapper<AutoflowStep>()
				.eq(AutoflowStep::getFlowId, flowId).eq(BaseEntity::getIsDel, false)
				.orderByDesc(AutoflowStep::getStepNo);
		List<AutoflowStep> list = autoflowStepDao.list(eq);
		return R.success(list);
	}
	@ApiOperation("分页查询环节列表")
	@PostMapping("/autoFlow/step/page")
	public R<IPage<AutoflowStepPageVo>> page(@RequestBody @Valid AutoflowStepPageReq param) {
		LambdaQueryWrapper<AutoflowStep> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(AutoflowStep::getFlowId,param.getFlowId());
		if (StrUtil.isNotBlank(param.getSearchStr())) {
			lambdaQueryWrapper.like(AutoflowStep::getSearchStr, "%" + param.getSearchStr() + "%");
		}
		if (StrUtil.isNotBlank(param.getStepName())) {
			lambdaQueryWrapper.like(AutoflowStep::getStepName, "%" + param.getStepName() + "%");
		}
		lambdaQueryWrapper.orderByAsc(AutoflowStep::getStepNo);
		IPage<AutoflowStep> pb = autoflowStepDao.page(
			new Page<>(param.getPage(), param.getPageSize()),
			lambdaQueryWrapper);
		Page<AutoflowStepPageVo> iPage = new Page<>();
		BeanUtil.copyProperties(pb, iPage);
		List<AutoflowStepPageVo> autoflowStepPageVos = new ArrayList<>();
		if (CollectionUtil.isNotEmpty(pb.getRecords())){
			for (int i = 0; i < pb.getRecords().size(); i++) {
				AutoflowStep line = pb.getRecords().get(i);
				AutoflowStepPageVo autoflowStepPageVo = new AutoflowStepPageVo();
				BeanUtil.copyProperties(line,autoflowStepPageVo);
				List<AutoflowStepPerson> list = autoflowStepPersonDao.list(new LambdaQueryWrapper<AutoflowStepPerson>()
					.eq(AutoflowStepPerson::getStepId, line.getId()).eq(BaseEntity::getIsDel, false));
				List<Long> userIds = list.stream().map(AutoflowStepPerson::getStepHandler).collect(Collectors.toList());
				if (CollectionUtil.isNotEmpty(userIds)){
					List<AuthUser> list1 = authUserDao.list(new LambdaQueryWrapper<AuthUser>().in(BaseEntity::getId, userIds));
					List<String> userNames = list1.stream().map(AuthUser::getName).collect(Collectors.toList());
					autoflowStepPageVo.setStepHandler(String.join(",", userNames));
				}
				List<AutoflowStepForm> formList = autoflowStepFormDao.list(new LambdaQueryWrapper<AutoflowStepForm>().eq(AutoflowStepForm::getStepId, line.getId()));
				if (CollectionUtil.isNotEmpty(formList)){
					List<Long> formIds = formList.stream().map(AutoflowStepForm::getFormId).collect(Collectors.toList());
					List<DiyForm> diyForm = formDao.listByIds(formIds);
					String formName = diyForm.stream().map(DiyForm::getName).collect(Collectors.joining(","));
					autoflowStepPageVo.setStepFormName(formName);
				}
				autoflowStepPageVo.setPersonList(userIds);
				autoflowStepPageVos.add(autoflowStepPageVo);
			}
		}
		iPage.setRecords(autoflowStepPageVos);
		return R.success(iPage);
	}
	@ApiOperation("查询环节表单列表")
	@PostMapping("/autoFlow/step/formList")
	public R<List<AutoflowStepFormVo>> formList(@RequestBody AutoflowStepIdReq autoflowStepIdReq) {
		LambdaQueryWrapper<AutoflowStepForm> eq = new LambdaQueryWrapper<AutoflowStepForm>()
				.eq(AutoflowStepForm::getStepId, autoflowStepIdReq.getStepId()).eq(BaseEntity::getIsDel, false)
				.orderByDesc(AutoflowStepForm::getCreateTime);
		List<AutoflowStepFormVo> autoflowStepFormVos = new ArrayList<>();
		List<AutoflowStepForm> list = autoflowStepFormDao.list(eq);
		if (CollectionUtil.isNotEmpty(list)){
			Map<Long, String> formMap = new HashMap<>();
			Map<Long, String> viewMap = new HashMap<>();
			List<Long> formIds = list.stream().map(AutoflowStepForm::getFormId).distinct().collect(Collectors.toList());
			if (CollectionUtil.isNotEmpty(formIds)){
				List<DiyForm> forms = formDao.listByIds(formIds);
				formMap=forms.stream().collect(Collectors.toMap(DiyForm::getId,DiyForm::getName));
			}
			List<Long> viewIds = list.stream().map(AutoflowStepForm::getViewId).distinct().collect(Collectors.toList());
			if (CollectionUtil.isNotEmpty(formIds)){
				List<DiyView> diyViews = diyViewDao.listByIds(viewIds);
				viewMap=diyViews.stream().collect(Collectors.toMap(DiyView::getId,DiyView::getName));
			}
			Map<Long, String> finalFormMap = formMap;
			Map<Long, String> finalViewMap = viewMap;
			list.forEach(line->{
				AutoflowStepFormVo autoflowStepFormVo = new AutoflowStepFormVo();
				BeanUtil.copyProperties(line,autoflowStepFormVo);
				autoflowStepFormVo.setFormName(finalFormMap.get(line.getFormId()));
				autoflowStepFormVo.setViewName(finalViewMap.get(line.getViewId()));
				autoflowStepFormVos.add(autoflowStepFormVo);
			});
		}
		return R.success(autoflowStepFormVos);
	}
	@ApiOperation("新增环节表单信息")
	@PostMapping("/autoFlow/step/addStepForm")
	public R addStepForm(@RequestBody AutoflowStepFormAddReq addReq) {
		autoflowStepFormDao.remove(new LambdaQueryWrapper<AutoflowStepForm>().eq(AutoflowStepForm::getStepId, addReq.getStepId()));
		addReq.getFormInfo().forEach(line -> {
			AutoflowStepForm autoflowStepForm = new AutoflowStepForm();
			BeanUtil.copyProperties(line, autoflowStepForm);
			autoflowStepForm.setStepId(addReq.getStepId());
			autoflowStepFormDao.save(autoflowStepForm);
		});
		return R.success();
	}
}
